﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WeChatAPIDemo
{
    public class HttpHelper
    {
        public static string GetHtmlSource(string Url)
        {
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url.ToString());
                myRequest.ServicePoint.Expect100Continue = true;
                myRequest.Method = "GET";
                myRequest.Timeout = 30000;
                myRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)";
                myRequest.KeepAlive = true;
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                string htmlSource = "";
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    htmlSource = reader.ReadToEnd();
                }
                return htmlSource;
            }
            catch (Exception ex) { return ex.Message; }
        }

        public static string Submit(string Url, byte[] postData)
        {
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url.ToString());

                myRequest.Method = "Post";
                myRequest.Timeout = 30000;
                myRequest.KeepAlive = true;
                myRequest.AllowAutoRedirect = true;
                myRequest.AllowWriteStreamBuffering = true;
                myRequest.ServicePoint.Expect100Continue = true;
                myRequest.Headers["Cache-control"] = "no-cache";
                myRequest.Headers["Accept-Language"] = "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2";
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentType = "application/json";
                myRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                myRequest.Accept = "application/json";
                myRequest.ContentLength = postData.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(postData, 0, postData.Length);
                newStream.Close();
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string html = reader.ReadToEnd();
                reader.Close();
                return html;
            }
            catch (Exception ex) { return ex.Message; }
        }
    }
}
